

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card mb-4">
            <div class="card-body">
                <h3 class="card-title text-center mb-4">记账</h3>
                <div class="text-end mb-4">
                    <button type="button" class="btn btn-danger" onclick="showResetConfirm()">
                        重置账户
                    </button>
                </div>
                <form action="{{ url_for('save_transaction') }}" method="POST" id="transactionForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="amount" class="form-label">金额</label>
                                <input type="number" step="0.01" class="form-control" id="amount" name="amount" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="type" class="form-label">类型</label>
                                <select class="form-select" id="type" name="type" required onchange="updateCategoryList(this.value)">
                                    <option value="income" selected>收入</option>
                                    <option value="expense">支出</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="category" class="form-label">分类</label>
                        <select class="form-select" id="category" name="category_id" required>
                            {% for category in categories %}
                            <option value="{{ category.id }}">{{ category.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">描述</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="date" class="form-label">日期</label>
                        <input type="date" class="form-control" id="date" name="date" value="{{ current_date }}" required>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>

<script>
// 更新分类列表函数
function updateCategoryList(transactionType) {
    // 获取当前类型的所有分类
    fetch(`/api/categories?type=${transactionType}`)
        .then(response => response.json())
        .then(data => {
            const categorySelect = document.getElementById('category');
            // 清空当前选项
            categorySelect.innerHTML = '';
            // 添加新的选项
            data.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                categorySelect.appendChild(option);
            });
        })
        .catch(error => console.error('Error:', error));
}

// 页面加载时更新分类列表
window.onload = function() {
    const typeSelect = document.getElementById('type');
    updateCategoryList(typeSelect.value);
    
    // 初始化加载更多按钮
    const loadMoreBtn = document.getElementById('loadMoreBtn');
    let currentPage = 1;
    const pageSize = 10;

    loadMoreBtn.addEventListener('click', function() {
        currentPage++;
        loadMoreTransactions(currentPage);
    });
}

// 加载更多交易记录
function loadMoreTransactions(page) {
    const loadMoreBtn = document.getElementById('loadMoreBtn');
    loadMoreBtn.disabled = true;
    loadMoreBtn.textContent = '加载中...';

    fetch(`/api/transactions?page=${page}&size=${pageSize}`)
        .then(response => response.json())
        .then(data => {
            const transactionList = document.getElementById('transactionList');
            data.transactions.forEach(transaction => {
                const row = document.createElement('tr');
                row.className = 'transaction-item';
                row.innerHTML = `
                    <td class="transaction-date">${new Date(transaction.date).toLocaleString()}</td>
                    <td>
                        <span class="${transaction.type === 'income' ? 'income' : 'expense'}">
                            ${transaction.type}
                        </span>
                    </td>
                    <td>${transaction.category.name}</td>
                    <td>
                        <span class="${transaction.type === 'income' ? 'income' : 'expense'}">
                            ${transaction.amount.toFixed(2)}
                        </span>
                    </td>
                    <td>${transaction.description}</td>
                `;
                transactionList.appendChild(row);
            });

            if (data.totalPages <= page) {
                loadMoreBtn.style.display = 'none';
            } else {
                loadMoreBtn.disabled = false;
                loadMoreBtn.textContent = '加载更多';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            loadMoreBtn.disabled = false;
            loadMoreBtn.textContent = '加载更多';
            alert('加载交易记录时出错');
        });
}

// 显示重置确认对话框
function showResetConfirm() {
    if (confirm('警告：这将删除您所有的账户信息，包括分类、交易记录和储蓄目标。确定要继续吗？')) {
        resetAccount();
    }
}

// 重置账户
async function resetAccount() {
    try {
        const response = await fetch('/reset_account', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('账户已重置成功');
            // 重置页面
            window.location.reload();
        } else {
            alert('重置账户时出错：' + result.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('重置账户时出错');
    }
}

// 处理表单提交
const form = document.getElementById('transactionForm');
form.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });

    fetch('/save_transaction', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert('交易保存成功');
            // 重置表单
            form.reset();
            // 更新交易列表
            loadMoreTransactions(1);
        } else {
            alert(result.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('保存交易时出错');
    });
});
</script>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <h3 class="card-title text-center mb-4">最近交易</h3>
                <div class="table-responsive">
                    <table class="table table-hover" id="transactionsTable">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>类型</th>
                                <th>分类</th>
                                <th>金额</th>
                                <th>描述</th>
                            </tr>
                        </thead>
                        <tbody id="transactionList">
                            {% for transaction in recent_transactions %}
                            <tr class="transaction-item">
                                <td class="transaction-date">{{ transaction.date.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    <span class="{% if transaction.type == 'income' %}income{% else %}expense{% endif %}">
                                        {{ transaction.type }}
                                    </span>
                                </td>
                                <td>{{ transaction.category.name }}</td>
                                <td>
                                    <span class="{% if transaction.type == 'income' %}income{% else %}expense{% endif %}">
                                        {{ "%.2f"|format(transaction.amount) }}
                                    </span>
                                </td>
                                <td>{{ transaction.description }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                <div class="text-center mt-3">
                    <button class="btn btn-outline-primary" id="loadMoreBtn">加载更多</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 更新分类列表函数
function updateCategoryList(transactionType) {
    // 获取当前类型的所有分类
    fetch(`/api/categories?type=${transactionType}`)
        .then(response => response.json())
        .then(data => {
            const categorySelect = document.getElementById('category');
            // 清空当前选项
            categorySelect.innerHTML = '';
            // 添加新的选项
            data.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                categorySelect.appendChild(option);
            });
        })
        .catch(error => console.error('Error:', error));
}

// 页面加载时更新分类列表
window.onload = function() {
    const typeSelect = document.getElementById('type');
    updateCategoryList(typeSelect.value);
    
    // 初始化加载更多按钮
    const loadMoreBtn = document.getElementById('loadMoreBtn');
    let currentPage = 1;
    const pageSize = 10;

    loadMoreBtn.addEventListener('click', function() {
        currentPage++;
        loadMoreTransactions(currentPage);
    });
}

// 加载更多交易记录
function loadMoreTransactions(page) {
    const loadMoreBtn = document.getElementById('loadMoreBtn');
    loadMoreBtn.disabled = true;
    loadMoreBtn.textContent = '加载中...';

    fetch(`/api/transactions?page=${page}&size=${pageSize}`)
        .then(response => response.json())
        .then(data => {
            const transactionList = document.getElementById('transactionList');
            data.transactions.forEach(transaction => {
                const row = document.createElement('tr');
                row.className = 'transaction-item';
                row.innerHTML = `
                    <td class="transaction-date">${new Date(transaction.date).toLocaleString()}</td>
                    <td>
                        <span class="${transaction.type === 'income' ? 'income' : 'expense'}">
                            ${transaction.type}
                        </span>
                    </td>
                    <td>${transaction.category.name}</td>
                    <td>
                        <span class="${transaction.type === 'income' ? 'income' : 'expense'}">
                            ${transaction.amount.toFixed(2)}
                        </span>
                    </td>
                    <td>${transaction.description}</td>
                `;
                transactionList.appendChild(row);
            });

            if (data.totalPages <= page) {
                loadMoreBtn.style.display = 'none';
            } else {
                loadMoreBtn.disabled = false;
                loadMoreBtn.textContent = '加载更多';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            loadMoreBtn.disabled = false;
            loadMoreBtn.textContent = '加载更多';
            alert('加载交易记录时出错');
        });
}

// 显示重置确认对话框
function showResetConfirm() {
    if (confirm('警告：这将删除您所有的账户信息，包括分类、交易记录和储蓄目标。确定要继续吗？')) {
        resetAccount();
    }
}

// 重置账户
async function resetAccount() {
    try {
        const response = await fetch('/reset_account', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('账户已重置成功');
            // 重置页面
            window.location.reload();
        } else {
            alert('重置账户时出错：' + result.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('重置账户时出错');
    }
}
</script>
</script>
{% endblock %}
